import React, { PureComponent } from 'react'
import { StyleSheet, View, Image, Text, TouchableOpacity, Dimensions, FlatList, TouchableHighlight } from 'react-native'
import Color from '../../widget/color'
import NavigationItem from '../../widget/NavigationItem'
import HomeMenuView from './HomeMenuView'
import HomeGridView from './HomeGridView'
import HomeListView from './HomeListView'
import api from '../../api'


type Props = {

}
type State = {
  discounts: Array<Object>,
  dataList: Array<Object>,
  page: number,
  refreshing: boolean,
}
class HomeScene extends PureComponent<Props, State>{
  static navigationOptions = () => ({
    headerStyle: {
      backgroundColor: Color.primary
    },
    headerTitle: (
      <TouchableOpacity style={styles.searchBar}>
        <Image source={require('../../img/home/search_icon.png')} style={styles.icon}></Image>
        <Text style={styles.text}>搜索</Text>
      </TouchableOpacity>
    ),
    headerLeft: (
      <NavigationItem title="定位" titleStyle={{ color: '#ffffff' }} onPress={() => {
        alert('定位')
      }} />
    ),
    headerRight: (
      <NavigationItem icon={require('../../img/home/icon_navigationItem_message_white.png')} onPress={() => {
        alert('通知')
      }} />
    )
  })
  constructor(props: Props) {
    super(props)

    this.state = {
      discounts: [],
      dataList: [],
      refreshing: false,
      page: 1
    }
  }

  componentDidMount () {
    this.requestData()
  }
  requestData = async (page = 1) => {
    try {
      this.setState({
        refreshing: true
      })
      // let response = await fetch(api.getEleList(page))
      // let json = await response.json()
      // alert(JSON.stringify(json))
      let json = api.ELE
      let dataList = json.items.map(
        (info) => {
          let data = info.restaurant
          return {
            id: data.id,
            imageUrl: 'https://fuss10.elemecdn.com/9/47/4080f13087cfcda6350fb2c077903png.png',
            title: data.name,
            subtitle: `￥${data.piecewise_agent_fee.rules[0].price}起送 | 配送费${data.piecewise_agent_fee.rules[0].fee}`,
            description: data.activities,
            address: data.address
          }
        }
      )
      this.setState({
        dataList: this.state.dataList.concat(dataList),
        refreshing: false,
        page: page + 1
      })
    } catch (error) {
      alert(error)
      this.setState({ refreshing: false })
    }
  }
  onGridItem = (e) => {
    this.props.navigation.navigate('WebScene', { uri: e.tplurl }) //跳转页面
  }
  renderHeader = () => {
    return (
      <View>
        <HomeMenuView menuIcons={api.menuInfo} />
        <HomeGridView onGridItem={this.onGridItem} />
        <View style={styles.TitleWrap}>
          <Text style={styles.TitleWrapText}>猜你会喜欢</Text>
        </View>
      </View>
    )
  }
  renderItem = ({ item }) => (
    <View>
      <HomeListView info={item} />
    </View>
  )
  onRefresh = () => {

  }
  onEndReached = () => {
    this.requestData(this.state.page)
  }
  render () {
    return (
      <View>
        <FlatList
          ListHeaderComponent={() => this.renderHeader()}
          data={this.state.dataList}
          keyExtractor={(item, index) => item.id}
          renderItem={this.renderItem}
          onRefresh={this.onRefresh}   //设置下拉刷新一定要设置 refreshing
          refreshing={this.state.refreshing}
          onEndReachedThreshold={0.1}
          onEndReached={() => this.onEndReached()}
        />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Color.paper
  },
  searchBar: {
    flexDirection: 'row',  //该属性决定主轴的方向（即项目的排列方向）
    width: Dimensions.get('window').width * 0.7,
    // marginLeft: Dimensions.get('window').width * 0.15,  //安卓不会居中？
    height: 30,
    borderRadius: 19,
    backgroundColor: '#ffffff',
    justifyContent: 'center',  //定义了伸缩项目在主轴线的对齐方式
    alignItems: 'center' //定义项目在交叉轴上如何对齐，可以把其想像成侧轴（垂直于主轴）的“对齐方式”。
  },
  icon: {
    width: 20,
    height: 20,
    marginRight: 5,
  },
  text: {
    fontSize: 14
  },
  TitleWrap: {
    backgroundColor: '#ffffff'
  },
  TitleWrapText: {
    fontSize: 20,
    margin: 10
  }
})

export default HomeScene
